package com.example.forwardmessages

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*

/**
 * 短信列表适配器，用于将短信数据显示在RecyclerView中
 */
class SmsAdapter(private val smsList: List<SmsMessage>) : 
    RecyclerView.Adapter<SmsAdapter.SmsViewHolder>() {

    // 日期格式化工具
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

    /**
     * 创建ViewHolder
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SmsViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.sms_item, parent, false)
        return SmsViewHolder(view)
    }

    /**
     * 绑定ViewHolder数据
     */
    override fun onBindViewHolder(holder: SmsViewHolder, position: Int) {
        val sms = smsList[position]
        holder.senderTextView.text = sms.address
        holder.contentTextView.text = sms.body
        holder.timeTextView.text = dateFormat.format(Date(sms.date))
    }

    /**
     * 获取列表项数量
     */
    override fun getItemCount(): Int {
        return smsList.size
    }

    /**
     * ViewHolder类，用于缓存列表项的视图
     */
    class SmsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val senderTextView: TextView = itemView.findViewById(R.id.sender_text)
        val contentTextView: TextView = itemView.findViewById(R.id.content_text)
        val timeTextView: TextView = itemView.findViewById(R.id.time_text)
    }
}